package cn.ac.iscas.base.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author lirenshen
 * @version 1.0
 * @date 2022/3/2 10:20
 * @since jdk11
 */
@MappedTypes(String.class)
public class AesEncryptHandler extends BaseTypeHandler<String> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        if (StringUtils.isNotBlank(parameter)) {
            ps.setString(i, encrypt(parameter));
        } else {
            ps.setString(i, null);
        }
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String columnValue = rs.getString(columnName);
        return encrypt(columnValue);
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String columnValue = rs.getString(columnIndex);
        return decrypt(columnValue);
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        String columnValue = cs.getString(columnIndex);
        return decrypt(columnValue);
    }

    private String encrypt(String parameter) {
        String value = null;
        try {
            value = AesUtils.aesEncrypt(parameter);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }

    private String decrypt(String parameter) {
        String value = null;
        try {
            value = AesUtils.aesDecrypt(parameter);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }
}
